﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Service.Interface;
using Domain;
using Clannan.Helper;
using Clannan.ActionFilter;
using System.Web.Security;
using Clannan.Models.ViewModel;

namespace Clannan.Controllers
{
    public class HomeController : Controller
    {
        public IUserInfoService UserInfoService;
        public INoteBookService NoteBookService;
        public IAreaService AreaService;

        /// <summary>
        /// 首页
        /// </summary>
        /// <returns></returns>

        public void Index()
        {
            //throw new Exception("123132");
        }

        /// <summary>
        /// 登陆
        /// </summary>
        /// <returns></returns>
        public ActionResult Login()
        {
            return View();
        }

        //[AcceptVerbs(HttpVerbs.Post)]
        //public ActionResult Login(LoginModel loginModel, FormCollection form)
        //{
        //    string validateCode = (Session["ValidateCode"] ?? "").ToString();
        //    if (ModelState.IsValid)//服务端数据验证
        //    {
        //        if (validateCode != form["Code"].ToString())//验证码错误
        //        {
        //            ModelState.AddModelError("Code", "验证码错误!");
        //            return View();
        //        }
        //        UserInfo userinfo = this.UserInfoService.Get(loginModel.Name.Trim(), loginModel.Password);
        //        if (userinfo != null)//登陆成功
        //        {
        //            string roleName = this.UserInfoService.GetUserInfoRoleName(userinfo.Name);//获取用户角色
        //            AddCookit addCookit = new AddCookit();
        //            addCookit.AddCookitToLoginUser(userinfo.ID.ToString(), roleName);//添加Cookit到客户端
        //            if (Request.QueryString["ReturnUrl"] != null)//判断是否需要重定向
        //            {
        //                string returnUrl = Request.QueryString["ReturnUrl"];
        //                return Redirect(returnUrl);
        //            }   
        //            return RedirectToAction("Index", "Home");
        //        }
        //        ModelState.AddModelError("Error", "密码或用户名错误！");
        //        return View();
        //    }
        //    return View(loginModel);
        //}

        /// <summary>
        /// 登陆
        /// </summary>
        /// <param name="name">用户名</param>
        /// <param name="password">密码</param>
        /// <param name="validateCode">验证码</param>
        /// <param name="url">重定向地址</param>
        /// <returns></returns>
        public JsonResult LoginIsPass(string name, string password, string validateCode, string keepLogin,string url)
        {
            //验证
            if (validateCode != (Session["ValidateCode"] ?? "").ToString())
            {
                return Json(new { Message = 0, Error = "验证码错误" });
            }
            if (string.IsNullOrEmpty(name) || string.IsNullOrEmpty(password))
            {
                return Json(new { Message = 0, Error = "用户名或密码不能为空" });
            }

            UserInfo userinfo = this.UserInfoService.Get(name, password);
            if (userinfo != null)//登陆成功
            {
                //添加Cookit到客户端
                AddCookit addCookit = new AddCookit();
                int dayCount;//保存Cookit时间
                if (keepLogin == "true")
                {
                    dayCount = 365;
                }
                else
                {
                    dayCount = 1;
                }
                addCookit.AddCookitToLoginUser(userinfo.ID.ToString(), userinfo.Role.Name, dayCount);

                return Json(new { Message = 1 });
            }
            else
            {
                return Json(new { Message = 0, Error = "用户名或密码错误，登陆失败！" });
            }
        }

   
        /// <summary>
        /// 将生成的验证码存入Session，并输出验证码图片
        /// </summary>
        /// <returns></returns>
        public ActionResult AuthCode()
        {
            ValidateCode validateCode = new ValidateCode();
            string code = validateCode.CreateValidateCode(4);
            Session["ValidateCode"] = code;
            byte[] bytes = validateCode.CreateValidateGraphic(code);

            return File(bytes, @"image/jpeg");
        }

        /// <summary>
        /// 注销
        /// </summary>
        /// <returns></returns>
        public ActionResult LogOut()
        {
            FormsAuthentication.SignOut();

            return RedirectToAction("Index", "Home");
        }

        /// <summary>
        /// 注册
        /// </summary>
        /// <returns></returns>
        public ActionResult Regist()
        {
            return View();
        }

        /// <summary>
        /// 注册Post
        /// </summary>
        /// <param name="userInfo">用户信息类</param>
        /// <param name="form">表单数据</param>
        /// <returns></returns>
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Regist(UserInfo userInfo, FormCollection form)
        {
            if (ModelState.IsValid)
            {
                //验证
                if ((Session["ValidateCode"] ?? "").ToString() != form["Code"].ToString())
                {
                    ModelState.AddModelError("Code", "验证码错误!");
                    return View();
                }
                ModelState.Clear();
                if (ModelState.Count == 0)
                {
                    if (this.UserInfoService.Get(userInfo.Name) != null)//判断用户名是否存在
                    {
                        ModelState.AddModelError("NameRepeat", " 用户名已存在！请重新输入！");
                    }
                    if (this.UserInfoService.GetByEmail(userInfo.Email) != null)//判断用户名是否存在
                    {
                        ModelState.AddModelError("EmailRepeat", " 邮箱已存在！请重新输入！");
                    }
                    if (ModelState.Count != 0)
                    {
                        return View(userInfo);
                    }
                }

                //保存用户资料
                userInfo.RegistData = DateTime.Now;
                userInfo.Role = new Role { ID = 1 };
                userInfo.VerifyCode = Guid.NewGuid();
                userInfo.Activate = false;
                this.UserInfoService.Save(userInfo);

                try
                {
                    //发送邮件，等待用户激活账号
                    SendEmail sendEmail = new SendEmail();
                    sendEmail.Send(userInfo.Email, "恭喜你注册成功！", @"<a href=http://" + Request.ServerVariables["HTTP_HOST"] + "/home/verifysuccess?id=" + userInfo.ID + "&guid=" + userInfo.VerifyCode + " >点我验证啊</a>");
                }
                catch //邮件发送失败，返回错误页
                {
                    return View("Error");
                }

                return RedirectToAction("WaitingVerify", "Home", new { id = userInfo.ID });
            } 

            return View(userInfo);
        }

        /// <summary>
        /// 判断用户名是否重复
        /// </summary>
        /// <param name="name">用户名</param>
        /// <returns></returns>
        public JsonResult NameRepeat(string name)
        {
            if (this.UserInfoService.Get(name) == null)//用户名不存在
            {
                return Json(new { message = 1 });
            }
            else
            {
                return Json(new { message = 0 });
            }
        }

        /// <summary>
        /// 判断邮箱是否重复
        /// </summary>
        /// <param name="email">邮箱</param>
        /// <returns></returns>
        public JsonResult EmailRepeat(string email)
        {
            if (this.UserInfoService.GetByEmail(email) == null)//邮箱不存在
            {
                return Json(new { message = 1 });
            }
            else
            {
                return Json(new { message = 0 });
            }
        }

        /// <summary>
        /// 注册成功，等待发送邮件，激活账号
        /// </summary>
        /// <param name="userID">用户ID</param>
        /// <returns></returns>
        public ActionResult WaitingVerify(string userID)
        {
            string url = @"<a href='http://" + Request.ServerVariables["HTTP_HOST"] + "/Home/ReSendVerify/" + userID + "'>点我</a>";
            ViewData["url"] = url;

            return View();
        }

        /// <summary>
        /// 重新发送验证信息
        /// </summary>
        /// <param name="userID">用户ID</param>
        /// <returns></returns>
        public JsonResult ReSendVerify(int userID)
        {
            UserInfo userInfo = this.UserInfoService.Get(userID);
            if (userInfo.Activate == false)//如果用户账号未激活，则重新发送邮件
            {
                SendEmail sendEmail = new SendEmail();
                sendEmail.Send(userInfo.Email, "恭喜你注册成功！", @"<a href=http://" + Request.ServerVariables["HTTP_HOST"] + "/home/verifysuccess?id=" + userInfo.ID + "&guid=" + userInfo.VerifyCode + " >点我验证啊</a>");

                return Json(new { message = 1 });
            }
            else
            {
                return Json(new { message = 0 });
            }
        }

        /// <summary>
        /// 激活成功
        /// </summary>
        /// <returns></returns>
        public ActionResult VerifySuccess()
        {
            int userID = Convert.ToInt32(Request.QueryString["id"]);
            UserInfo userInfo = this.UserInfoService.Get(userID);
            if (userInfo.VerifyCode.ToString() == Request.QueryString["guid"])
            {
                //激活账号,添加用户默认笔记本、默认分区
                this.NoteBookService.SaveNoteBookAndArea(userInfo);
                ViewData["Message"] = "恭喜你激活账号成功！！！";
            }
            else
            {
                ViewData["Message"] = "对不起，你的账号激活失败！！！";
            }

            return View();
        }

        /// <summary>
        /// 获取当前用户名
        /// </summary>
        /// <returns></returns>
        public JsonResult RequestUsername()
        {
            if (User.Identity.Name == "")
            {
                return Json(null);
            }
            else
            {
                return Json(this.UserInfoService.Get(User.Identity.Name).Name);
            }
        }

    }

}
